<template>
  <div>个人协议

    <div
    v-for="(item, index) in itemList"
    :key="index"
    class="list-item"
    @click="toggleFollow(index)">
    <img :src="item.avatar" alt="头像" class="avatar" />
    <span>{{ item.name }}</span>
    <span v-if="isFollowed[index]">已关注</span>
    <span v-else>关注</span>
  </div>


  </div>

  
</template>

<script setup lang='ts'>
// import { ref } from 'vue';
import { ref, onMounted } from 'vue';

// 模拟的列表数据
const itemList = ref([
  {
    name: '用户1',
    avatar: 'https://example.com/avatar1.jpg'
  },
  {
    name: '用户2',
    avatar: 'https://example.com/avatar2y.jpg'
  },
  {
    name: '用户3',
    avatar: 'https://example.com/avatar3.jpg'
  }
]);

// 定义响应式数组，用于存储每个列表项的关注状态
const isFollowed = ref([]);

// 在组件挂载时，从本地存储读取关注状态并初始化
onMounted(() => {
  const storedFollowed = localStorage.getItem('followedList');
  if (storedFollowed) {
    isFollowed.value = JSON.parse(storedFollowed);
  } else {
    // 如果本地存储中没有数据，初始化关注状态数组为全false
    isFollowed.value = new Array(itemList.value.length).fill(false);
  }
});

// 定义点击事件处理函数，用于切换关注状态并更新本地存储
const toggleFollow = (index) => {
  isFollowed.value[index] =!isFollowed.value[index];
  updateLocalStorage();
};

// 定义更新本地存储的函数
const updateLocalStorage = () => {
  localStorage.setItem('followedList', JSON.stringify(isFollowed.value));
};
</script>

<style scoped>
</style>